﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.RunningSimulation.SimulationFileComparer
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using EngineeringInternalExtension;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using Tecnomatix.Engineering;


namespace DnProcessSimulateCommands.RunningSimulation;

public class SimulationFileComparer : SimulationFileAccessor
{
  private StreamReader m_file;
  private StreamWriter m_file_differences;
  private bool m_wasError;
  private int m_numOfDiffs;
  private List<string> m_origLinesBuffer = new List<string>();
  private double m_maxDiff;
  private double m_HEADER_NUMBER_LINES = 22.0;
  private const string DOUBLE_EXTENSION = "DOUBLE_";

  public override void openFile(string path)
  {
    this.closeFile();
    if (TxApplicationEx.DoesKinUseDoubles())
    {
      string extension = "DOUBLE_" + Path.GetExtension(path).TrimStart('.');
      path = Path.ChangeExtension(path, extension);
    }
    this.m_file = new StreamReader(path);
    for (int index = 0; (double) index < this.m_HEADER_NUMBER_LINES; ++index)
      this.m_file.ReadLine();
    string str = path;
    if (TxApplication.PlatformMode - 1 <= 1)
    {
      string extension = Path.GetExtension(path);
      int startIndex = path.LastIndexOf(extension, StringComparison.InvariantCultureIgnoreCase);
      if (startIndex >= 0)
        str = path.Remove(startIndex) + this.GetPlatformModeSuffix() + extension;
    }
    this.m_file_differences = new StreamWriter($"{str}_diff({Environment.UserName})");
    this.m_maxDiff = 0.0;
  }

  private string GetPlatformModeSuffix()
  {
    TxPlatformMode platformMode = TxApplication.PlatformMode;
    if (platformMode == 1)
      return "_VIEW";
    return platformMode == 2 ? "_VCLT" : string.Empty;
  }

  public override void closeFile()
  {
    if (this.m_file != null)
    {
      this.m_file.Close();
      this.m_file = (StreamReader) null;
    }
    if (this.m_file_differences == null)
      return;
    this.m_file_differences.Flush();
    this.m_file_differences.Close();
    this.m_file_differences = (StreamWriter) null;
  }

  internal void VerifyEndOFBaseLineContent()
  {
    string first = "";
    if (this.m_origLinesBuffer != null && this.m_origLinesBuffer.Count > 0)
      first = this.m_origLinesBuffer[0];
    else if (this.m_file != null)
      first = this.m_file.ReadLine();
    if (!string.IsNullOrEmpty(first) && this.m_file_differences != null)
    {
      this.m_file_differences.WriteLine("There is more content in the base line");
      ++this.m_numOfDiffs;
      this.error(first, "");
    }
    if (this.m_maxDiff <= 0.0 || this.m_file_differences == null)
      return;
    this.m_file_differences.WriteLine("**********************The max difference value is: " + this.m_maxDiff.ToString());
  }

  public override void accessFile(string line, bool ignore = false)
  {
    if (!ignore)
    {
      while (this.m_origLinesBuffer.Count < 50)
      {
        string str = this.m_file.ReadLine();
        if (str != null)
          this.m_origLinesBuffer.Add(str);
        else
          break;
      }
      bool flag = false;
      if (this.m_origLinesBuffer.Count > 0)
      {
        for (int index = 0; index < this.m_origLinesBuffer.Count; ++index)
        {
          if (this.SmartCompare(line, this.m_origLinesBuffer[index]))
          {
            this.m_origLinesBuffer.RemoveAt(index);
            flag = true;
            break;
          }
        }
        if (!flag)
        {
          ++this.m_numOfDiffs;
          this.error(this.m_origLinesBuffer[0], line);
          line = "ERROR" + line;
        }
      }
      else
      {
        ++this.m_numOfDiffs;
        this.error("End Of File", line);
        line = "ERROR" + line;
      }
    }
    this.m_file_differences.WriteLine(line);
  }

  private bool SmartCompare(string s1, string s2)
  {
    bool flag = false;
    if (s1 == null || s2 == null)
      return flag;
    if (s1.Contains("[") && s1.Contains("]"))
    {
      while (s1.Length > 0)
      {
        int fromIndexS1 = s1.IndexOf("[");
        int fromIndexS2 = s2.IndexOf("[");
        int tillIndexS1 = s1.IndexOf("]");
        int tillIndexS2 = s2.IndexOf("]");
        if (fromIndexS1 == 0 && fromIndexS2 == 0 && tillIndexS1 > 0 && tillIndexS2 > 0)
        {
          if (!this.CompareDoubles(ref s1, tillIndexS1, ref s2, tillIndexS2))
            break;
        }
        else if (fromIndexS1 <= 0 || fromIndexS2 <= 0 || !this.CompareStrings(ref s1, fromIndexS1, ref s2, fromIndexS2))
          break;
      }
    }
    if (s1 == s2)
      flag = true;
    return flag;
  }

  private bool CompareStrings(ref string s1, int fromIndexS1, ref string s2, int fromIndexS2)
  {
    bool flag = true;
    string str1 = s1.Substring(0, fromIndexS1);
    string str2 = s2.Substring(0, fromIndexS2);
    if (str1 == str2)
    {
      s1 = s1.Remove(0, str1.Length);
      s2 = s2.Remove(0, str2.Length);
    }
    else
      flag = false;
    return flag;
  }

  private bool CompareDoubles(ref string s1, int tillIndexS1, ref string s2, int tillIndexS2)
  {
    bool flag = true;
    string str1 = s1.Substring(1, tillIndexS1 - 1);
    string str2 = s2.Substring(1, tillIndexS2 - 1);
    string[] strArray1 = str1.Split(',');
    string[] strArray2 = str2.Split(',');
    if (strArray1.Length != strArray2.Length)
      flag = false;
    for (int index = 0; index < strArray1.Length & flag; ++index)
    {
      flag = false;
      double result1;
      double result2;
      if (double.TryParse(strArray1[index], out result1) && double.TryParse(strArray2[index], out result2))
      {
        double num = Math.Abs(result1 - result2);
        if (num < this.m_toleranceToCompare)
        {
          flag = true;
        }
        else
        {
          if (this.m_maxDiff < num)
          {
            this.m_maxDiff = num;
            break;
          }
          break;
        }
      }
      else
        break;
    }
    if (flag)
    {
      s1 = s1.Remove(0, tillIndexS1 + 1);
      s2 = s2.Remove(0, tillIndexS2 + 1);
    }
    return flag;
  }

  public override int getNumOfDiffs() => this.m_numOfDiffs;

  public virtual void error(string first, string second)
  {
    if (!this.m_wasError)
    {
      int num = (int) MessageBox.Show($"This line in the file:\n \"{second}\"\nIs not equal to the result from of the simulation:\n \"{first}\"", "SimulationRecorder", MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
    this.m_wasError = true;
  }
}
